package 高频题;

public class 爱吃香蕉的珂珂_875 {
    public int minEatingSpeed(int[] piles, int H) {
        int left = 1, right = getMax(piles) + 1;
        while (left < right) {
            // 防止溢出
            int mid = left + (right - left) / 2;
            if (canFinish(piles, mid, H)) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }

    //以speed的速率是否能在h小时内吃完香蕉
    private boolean canFinish(int[] piles, int speed, int h) {
        int time = 0;
        for (int pile : piles) {
            time += timeOf(pile, speed);
        }
        return time <= h;
    }

    //以spped的速度吃N个香蕉要多久
    private int timeOf(int pile, int speed) {
        return (pile / speed) + ((pile % speed) > 0 ? 1 : 0);
    }

    //获取数组中的最大值
    private int getMax(int[] piles) {
        int max = 0;
        for (int num : piles) {
            max = Math.max(max, num);
        }
        return max;
    }
}
